<template>
<view class="uni-header">
			<label>
				店铺管理 / 新增店铺
			</label>
			
</view>
  <view class="uni-container">
    <uni-forms ref="form" :model="formData" validateTrigger="bind" :label-width="150">
      <uni-forms-item name="title" label="店铺名称" required>
        <uni-easyinput placeholder="店铺名称最少为2个汉字，最多为30个汉字，不要使用特殊字符" v-model="formData.title" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="categories" label="店铺分类" required>
        <uni-data-picker placeholder="请选择店铺分类,务必确保正确" v-model="formData.categories" collection="opendb-mall-categories" orderby="sort asc" field="_id as value, name as text"></uni-data-picker>
      </uni-forms-item>
      <uni-forms-item name="region" label="店铺地址" required>
        <uni-data-picker self-field="code" placeholder="请选择店铺地址" parent-field="parent_code" v-model="formData.region" collection="opendb-city-china" orderby="value asc" field="code as value,name as text,eq(type,2) as isleaf"></uni-data-picker>
      </uni-forms-item>
      
	  <view class="add-shop-map">
	  	<iframe id="mapPage" width="100%" height="100%" frameborder=0
	  	    src="https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=ABIBZ-RGUC4-4DRU5-DRSD4-G5KQE-TOFTY&referer=myapp">
	  	</iframe>
	  </view>
	  <uni-forms-item name="address" label="详细地址" required>
	    <uni-easyinput disabled placeholder="请在地图中搜索地址,本输入框会自动获取" v-model="formData.address" trim="both"></uni-easyinput>
	  </uni-forms-item>
	  <uni-forms-item name="location" label="坐标" required>
	    <uni-easyinput disabled placeholder="请在地图中搜索地址,本输入框会自动获取" v-model="formData.location" trim="both"></uni-easyinput>
	  </uni-forms-item> 
	  <uni-forms-item name="poiname" label="地标名称" required>
	    <uni-easyinput disabled placeholder="请在地图中搜索地址,本输入框会自动获取" v-model="formData.poiname" trim="both"></uni-easyinput>
	  </uni-forms-item> 
	  
	  <uni-forms-item name="area" label="所属区域" required>
	  	 <uni-data-picker :localdata="area" v-model="formData.area_all" popup-title="请选择区域" @change="onchangeArea"></uni-data-picker>
	  </uni-forms-item>
	  
	  
      <uni-forms-item name="start_business_hours1" label="开始营业时间段1" required>
        <picker class="select-business-time-picker" mode="time" start="00:00" end="23:59" placeholder="请选择店铺开始营业时间" type="number" @change="binddata('start_business_hours1', $event.detail.value)" v-model="formData.start_business_hours1">
          <view v-if="formData.start_business_hours1">{{formData.start_business_hours1}}<label style="color:#4d85ff;margin-left:10px;">修改</label></view>
          <view v-else>
          			  <view class="select-business-time">
          			  	+ 点击选择时间
          			  </view>
          </view>
        </picker>
		<label @click="removeTime('start_business_hours1')" style="cursor:pointer;" title="清除时间">
			<uni-icons type="refresh-filled" size="25" color="#999"></uni-icons>
		</label>
      </uni-forms-item>
      <uni-forms-item name="end_business_hours1" label="结束营业时间段1" required>
        <picker class="select-business-time-picker" mode="time" start="00:00" end="23:59" placeholder="请选择店铺结束营业时间" type="number" @change="binddata('end_business_hours1', $event.detail.value)" v-model="formData.end_business_hours1">
          <view v-if="formData.end_business_hours1">{{formData.end_business_hours1}}<label style="color:#4d85ff;margin-left:10px;">修改</label></view>
          <view v-else>
          			  <view class="select-business-time">
          			  	+ 点击选择时间
          			  </view>
          </view>
        </picker>
      </uni-forms-item>
      <uni-forms-item name="start_business_hours2" label="开始营业时间段2">
        <picker class="select-business-time-picker" mode="time" start="00:00" end="23:59" placeholder="请选择店铺开始营业时间" type="number" @change="binddata('start_business_hours2', $event.detail.value)" v-model="formData.start_business_hours2">
          <view v-if="formData.start_business_hours2">{{formData.start_business_hours2}} <label style="color:#4d85ff;margin-left:10px;">修改</label></view>
          <view v-else>
          			  <view class="select-business-time">
          			  	+ 点击选择时间
          			  </view>
          </view>
        </picker>
		<label @click="removeTime('start_business_hours2')" style="cursor:pointer;" title="清除时间">
			<uni-icons type="refresh-filled" size="25" color="#999"></uni-icons>
		</label>
      </uni-forms-item>
	  
      <uni-forms-item name="end_business_hours2" label="结束营业时间段2">
        <picker class="select-business-time-picker" mode="time" start="00:00" end="23:59" placeholder="请选择店铺结束营业时间" type="number" @change="binddata('end_business_hours2', $event.detail.value)" v-model="formData.end_business_hours2">
          <view v-if="formData.end_business_hours2">{{formData.end_business_hours2}}<label style="color:#4d85ff;margin-left:10px;">修改</label></view>
		  <view v-else>
			  <view class="select-business-time">
			  	+ 点击选择时间
			  </view>
		  </view>
        </picker>
      </uni-forms-item>
      <uni-forms-item name="logo" label="店铺logo(200*200)" required>
        <uni-file-picker file-mediatype="image" file-extname="jpg,png,gif" return-type="object" v-model="formData.logo"></uni-file-picker>
      </uni-forms-item>
      <uni-forms-item name="photo" label="店铺照片(尺寸无限制,系统会自动缩略)" required>
        <uni-file-picker file-mediatype="image" file-extname="jpg,png,gif" :limit="50" return-type="array" v-model="formData.photo"></uni-file-picker>
      </uni-forms-item>
      <uni-forms-item name="tel" label="手机号码">
        <uni-easyinput v-model="formData.tel" placeholder="请数据店铺联系手机号码,客户会通过此手机联系商家" trim="both"></uni-easyinput>
      </uni-forms-item>
	  <uni-forms-item name="start_delivery_price" label="起送费">
	    <uni-easyinput v-model="formData.start_delivery_price" placeholder="请输入起送费,客户购买需满足该金额才能配送" trim="both"></uni-easyinput>
	  </uni-forms-item>
	  <uni-forms-item name="delivery_price" label="配送费">
	    <uni-easyinput v-model="formData.delivery_price" placeholder="请输入配送费,添加商品时会默认采用此配送费" trim="both"></uni-easyinput>
	  </uni-forms-item>
	  <uni-forms-item name="pack_price" label="打包费">
	    <uni-easyinput v-model="formData.pack_price" placeholder="请输入打包费,添加商品时会默认采用此打包费" trim="both"></uni-easyinput>
	  </uni-forms-item>
      <uni-forms-item name="intro" label="简介" required>
        <uni-easyinput type="textarea" placeholder="请输入店铺简介,500字以内" v-model="formData.intro" trim="both"></uni-easyinput>
      </uni-forms-item>
	  
	  <uni-forms-item name="preferential" label="满减优惠">
		  <view class="preferential-box" v-for="(item,index) in formData.preferential">
			  <label>
				  满
			  </label>
			  <label>
				 <uni-easyinput style="width:120px;" type="number" placeholder="满足金额" v-model="formData.preferential[index].full" trim="both"></uni-easyinput> 
			  </label>
			  <label>
				  元
			  </label>
		  	  <label>
				  减
			  </label>
		  	  <label>
				  <uni-easyinput style="width:120px;" type="number" placeholder="减去金额" v-model="formData.preferential[index].reduce" trim="both"></uni-easyinput>
			  </label>
			  <label>
				  元
			  </label>
			  <label class="goods-add-sku-del" @click="delPreferential(index)">
				删除
			  </label>
		  	  
		  </view>
		  <view class="preferential-add" @click="addPreferential">
		  	增加一项满减优惠
		  </view>
		</uni-forms-item>
	  
	  <uni-forms-item name="is_book" label="提前预订">
	    <switch @change="binddata('is_book', $event.detail.value)" :checked="formData.is_book"></switch>
	  </uni-forms-item>
	  <uni-forms-item name="is_take_away" label="可否外卖">
	    <switch @change="binddata('is_take_away', $event.detail.value)" :checked="formData.is_take_away"></switch>
	  </uni-forms-item>
      <uni-forms-item name="disabled_status" label="店铺状态">
        <switch @change="binddata('disabled_status', $event.detail.value)" :checked="formData.disabled_status"></switch>
      </uni-forms-item>
      <uni-forms-item name="business_status" label="经营状态">
        <switch @change="binddata('business_status', $event.detail.value)" :checked="formData.business_status"></switch>
      </uni-forms-item>
      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
        <navigator open-type="navigateBack" style="margin-left: 15px;">
          <button class="uni-button" style="width: 100px;">返回</button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>
<style lang="scss" scoped>
	.goods-add-sku-del {
		width: 60px;
		height: 30px;
		line-height: 30px;
		text-align: center;
		color: #4177;
		float: left;
	}
	.preferential-add{float:left;width:100%;height:30px;line-height:30px;text-align: center;background:rgba(240,240,240,.3);color:#e7c000;margin-bottom:20px;font-size:13px;cursor:pointer;border:1px solid #e7c000;margin-top:30px;}
	.preferential-box label{float:left;line-height:35px;margin-right:20px;}
	.preferential-box{width:100%;float:left;margin-bottom:10px;}
	.select-business-time-picker{margin-top:8px;font-size:15px;}
	.select-business-time{width:120px;color:#666;line-height:30px;border:1px solid #666;text-align: center;border-radius: 3px;}
	.add-shop-map{height:500px;margin-bottom:50px;background:#f4f4f4;padding:20px;}
</style>
<script>
  import { validator } from '../../../js_sdk/validator/shop.js';

  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'shop';

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        result[key] = validator[key]
      }
    }
    return result
  }

  function numberRange(start, end) {
    return Array.from(new Array(end + 1).keys()).slice(start);
  }

  export default {
    data() {
      let formData = {
        "title": "",
		"area":null,
		"area_all":null,
        "categories": "",
        "region": "371726",
        "address": "",
		"location":"",
        "start_business_hours1": null,
        "end_business_hours1": null,
        "start_business_hours2": null,
        "end_business_hours2": null,
        "logo": null,
        "photo": [],
        "tel": "",
		"delivery_price":0,
		"start_delivery_price":0,
		"pack_price":0,
        "intro": "",
		"preferential":[
			{
			"full":'',
			"reduce":'',
			}
		],
		"is_book":true,
		"is_take_away":true,
        "disabled_status": true,
        "business_status": true,
		"create_uid":''
      }
      return {
		area:[],
        formData,
        formOptions: {
          "score_data": numberRange(0, 5),
          "score_index": null
        },
        rules: {
          ...getValidator(Object.keys(formData))
        }
      }
    },
    onReady() {
		var that = this;
		uni.getStorage({
			key:'uni-id-pages-userInfo',
			success:function(res){
				that.formData.create_uid = '64d5f86286206658e9bb7afe';
			}
		})
		var that = this;
		window.addEventListener('message', function(event) {
		        // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
		        var loc = event.data;
		        if (loc && loc.module == 'locationPicker') {//防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
				  that.formData.address = loc.poiaddress;
				  that.formData.location = new db.Geo.Point(loc.latlng.lng,loc.latlng.lat);
				  that.formData.poiname = loc.poiname;
		        }
		    }, false);
      this.$refs.form.setRules(this.rules)
	  this.getArea();
    },
    methods: {
		//设置区域
		onchangeArea(e){
			this.formData.area_all = e.detail.value;
			this.formData.area = e.detail.value[e.detail.value.length - 1];
		},
		//获取配送区域
		getArea(){
		 db.collection('region_city').get().then(res=>{
			 this.area = res.result.data;
		 });
		  
		},
		//删除营业时间
		removeTime(type){
		
			if(type=='start_business_hours1'){
				this.formData.start_business_hours1 = '';
				this.formData.end_business_hours1 = '';
			}else if(type=='start_business_hours2'){
				this.formData.start_business_hours2 = '';
				this.formData.end_business_hours2 = '';
			}
		},
		//删除一项满减优惠
		delPreferential(index){
			this.formData.preferential.splice(index, 1);
		},
		//增加一项满减优惠
		addPreferential(){
			this.formData.preferential.push(
				{
					"full":'',
					"reduce":''
				}
			);
		},
		binddata(field,e){
			switch(field){
				case 'start_business_hours1':
				this.formData.start_business_hours1 = e;
				break;
				case 'end_business_hours1':
				this.formData.end_business_hours1 = e;
				break;
				case 'start_business_hours2':
				this.formData.start_business_hours2 = e;
				break;
				case 'end_business_hours2':
				this.formData.end_business_hours2 = e;
				break;
				case 'disabled_status':
				this.formData.disabled_status = e;
				break;
				case 'business_status':
				this.formData.business_status = e;
				break;
				
				
				
			}
		},
      pickerChange(e, name) {
        this.formOptions[name + '_index'] = e.detail.value;
        this.formData[name] = this.formOptions[name + '_data'][e.detail.value];
        this.binddata(name, this.formData[name]);
      },
      /**
       * 验证表单并提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
        this.$refs.form.validate().then((res) => {
			  console.log(res);
			var data = this.formData;
			if(data.start_business_hours1){
				data.start_business_hours1 = data.start_business_hours1.substr(0,2)+''+data.start_business_hours1.substr(3,2);
				data.end_business_hours1 = data.end_business_hours1.substr(0,2)+''+data.end_business_hours1.substr(3,2);
				if(data.start_business_hours1 > data.end_business_hours1){
					uni.showToast({
						title: '开始时间不能大于结束时间',
						duration: 2000,
						icon:'error'
					});
					return false;
				}
			}
			
				
			if(data.start_business_hours2){
				data.start_business_hours2 = data.start_business_hours2.substr(0,2)+''+data.start_business_hours2.substr(3,2);
				data.end_business_hours2 = data.end_business_hours2.substr(0,2)+''+data.end_business_hours2.substr(3,2);
				if(data.start_business_hours2 > data.end_business_hours2){
					uni.showToast({
						title: '开始时间不能早于结束时间',
						duration: 2000,
						icon:'error'
					});
					return false;
				}
				
				if(data.start_business_hours2 < data.end_business_hours1){
					uni.showToast({
						title: '时间2不能早于时间1',
						duration: 2000,
						icon:'error'
					});
					return false;
				}
				
				
			}
			
			//配送费，起送费和打包费乘以100
			data.start_delivery_price = data.start_delivery_price * 100;
			data.delivery_price = data.delivery_price * 100;
			data.pack_price = data.pack_price * 100;
			
          return this.submitForm(data)
        }).catch((error) => {
			console.log(error);
        }).finally(() => {
          uni.hideLoading()
        })
      },
 
      /**
       * 提交表单
       */
      submitForm(value) {
        // 使用 clientDB 提交数据
        return db.collection(dbCollectionName).add(value).then((res) => {
			  console.log(res);
          uni.showToast({
            title: '新增成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateBack(), 500)
        }).catch((err) => {
			  console.log(err);
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      }
    }
  }
</script>
